"""
Python API项目主应用
"""
import os
from flask import Flask
from flask_cors import CORS
from flask_jwt_extended import JWTManager
from flask_sqlalchemy import SQLAlchemy
from flask_migrate import Migrate

from config.settings import settings

# 创建数据库实例
db = SQLAlchemy()
jwt = JWTManager()
migrate = Migrate()


def create_app():
    """创建Flask应用工厂函数"""
    app = Flask(__name__)

    # 加载配置
    app.config.from_object(settings)

    # 确保SQLALCHEMY_DATABASE_URI已设置
    if not app.config.get('SQLALCHEMY_DATABASE_URI'):
        app.config['SQLALCHEMY_DATABASE_URI'] = os.getenv('SQLALCHEMY_DATABASE_URI', 'sqlite:///app.db')

    # 修复MySQL连接字符串，使用mysql+mysqlconnector
    uri = app.config.get('SQLALCHEMY_DATABASE_URI', '')
    if uri.startswith('mysql://'):
        app.config['SQLALCHEMY_DATABASE_URI'] = uri.replace('mysql://', 'mysql+mysqlconnector://')
    
    # 初始化扩展
    db.init_app(app)
    jwt.init_app(app)
    migrate.init_app(app, db)
    
    # 配置CORS
    CORS(app, origins=settings.get("cors.origins", ["*"]))
    
    # 注册蓝图
    register_blueprints(app)
    
    # 注册错误处理器
    register_error_handlers(app)
    
    # 注册命令行命令
    register_commands(app)
    
    return app


def register_blueprints(app):
    """注册API蓝图"""
    try:
        from api.user.user_api import user_bp
        app.register_blueprint(user_bp, url_prefix="/api/v1/users")
    except ImportError as e:
        print(f"Warning: Could not import user_bp: {e}")

    try:
        from api.product.product_api import product_bp
        app.register_blueprint(product_bp, url_prefix="/api/v1/products")
    except ImportError as e:
        print(f"Warning: Could not import product_bp: {e}")

    try:
        from api.order.order_api import order_bp
        app.register_blueprint(order_bp, url_prefix="/api/v1/orders")
    except ImportError as e:
        print(f"Warning: Could not import order_bp: {e}")

    try:
        from api.sort.sort_api import sort_bp
        app.register_blueprint(sort_bp, url_prefix="/api/v1/sort")
    except ImportError as e:
        print(f"Warning: Could not import sort_bp: {e}")


def register_error_handlers(app):
    """注册错误处理器"""
    from common.utils import create_error_response
    
    @app.errorhandler(400)
    def bad_request(error):
        return create_error_response("Bad Request", 400)
    
    @app.errorhandler(404)
    def not_found(error):
        return create_error_response("Not Found", 404)
    
    @app.errorhandler(500)
    def internal_error(error):
        return create_error_response("Internal Server Error", 500)


def register_commands(app):
    """注册命令行命令"""
    @app.cli.command("init-db")
    def init_db():
        """初始化数据库"""
        db.create_all()
        print("数据库初始化完成")
    
    @app.cli.command("seed-db")
    def seed_db():
        """填充测试数据"""
        from scripts.generate_test_data import generate_test_data
        generate_test_data()
        print("测试数据填充完成")


# 创建应用实例
app = create_app()

if __name__ == "__main__":
    app.run(
        host=os.getenv("HOST", "0.0.0.0"),
        port=int(os.getenv("PORT", 5000)),
        debug=settings.get("debug", False)
    )